package org.lai.filter;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.lai.Utils.CurrentHolder;
import org.lai.Utils.JwtUtils;

import java.io.IOException;
@Slf4j
@WebFilter(urlPatterns = "/*") // 拦截所有请求
public class TokenFilter implements Filter {
    /**
     *
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request =  (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        // 1. 获取请求路径
        String path = request.getRequestURI();
        // 2. 判断是否是登录请求,如果路径中包含了 /login 是登录请求,直接放行
        if (path.contains("/login")){
            // 放行
            log.info("登录请求,放行");
            filterChain.doFilter(request,response);
            return;
        }
        // 3. 获取请求头中的token
        String token = request.getHeader("token"); // 获取请求头中的token
        // 4. 判断token是否为空, 如果为空, 拦截去登录(响应401状态码), 如果不为空, 放行
        if (token == null || token.equals(" ")){
            log.info("令牌为空,响应401");
            response.setStatus(401); // 响应状态码
            return;
        }
        // 5. 如果token存在, 校验令牌 -- 如果校验失败,响应401状态码, 如果校验成功,放行
        try {
            // Claims 本质就是一个Map,他继承的Map
            Claims claims = JwtUtils.parseJWT(token);
            Integer id = Integer.valueOf(claims.get("id").toString());
            CurrentHolder.setCurrentId(id);
            log.info("当前用户id为:{},将其存入ThreadLocal",id);
        } catch (Exception e) {
            log.info("令牌非法,响应401");
            response.setStatus(401); // 响应状态码
            return;
        }
        log.info("令牌合法,放行");
        // 放行调用相应的控制器方法,但是执行回还会回来
        filterChain.doFilter(request,response);
        // 删除ThreadLocal中的数据
        CurrentHolder.remove();
    }

}
